import React, { useState, useEffect } from 'react';
import { Space, Modal, message } from 'antd';
import { connect, Dispatch, history, Location } from 'umi';
import { PageContainer } from '@ant-design/pro-layout';
import ProCard from '@ant-design/pro-card';
import { CQ_DETAIL_INIT, FILL_CQ_DETAIL } from '@/actions/workbench';
import { ConnectState } from '@/models/connect';
import { AppItem } from '@/types/app';
import { DataItem } from '@/types/global';
import { UndoFillInfoTaskState, CqBaseInfoFormValue, CqDetailInfoFormValue, CqDetailInfoRecord, 
  CqUndoTaskType } from '@/types/workbench';
import { EMPTY_CQ_UNDO_TASK, EMPTY_CQ_BASE_INFO, EMPTY_CQ_DETAIL_INFO } from './common';
import { CqBaseInfoForm, CqDetailInfoForm } from './components';

interface FillCqDetailInfoProps {
  dispatch: Dispatch;
  location: Location;
  auditorData: DataItem[];
  designerData: DataItem[];
  loading: boolean;
  systemData: DataItem[];
  clusterData: DataItem[];
  appList: AppItem[];
}

/**
 * 录入需求详细信息
 */
const FillCqDetailInfo: React.FC<FillCqDetailInfoProps> = (props) => {
  // 当前表单信息
  const [formData, setFormData] = useState<CqUndoTaskType>(EMPTY_CQ_UNDO_TASK);
  const [baseInfo, setBaseInfo] = useState<CqBaseInfoFormValue>(EMPTY_CQ_BASE_INFO);

  useEffect(() => {
    console.log('FillCqDetailInfo.useEffect');
    // 获取页面传值
    const { location } = props;
    const { state } = location as { state: UndoFillInfoTaskState };
    // 未传值，直接返回登录
    if (!state) {
      goLogin();
      return;
    }
    const cqUndoTaskInfo = state && state.cqUndoTaskInfo;
    const cqDetailInfo = state && state.cqDetailInfo;
    if (cqUndoTaskInfo && cqDetailInfo) {
      // 满足条件，开始查询页面参数
      const { dispatch } = props;
      dispatch(CQ_DETAIL_INIT({}));
      const { cqCode, cqName, systemCode, clstCode, appCode } = cqUndoTaskInfo;
      const { auditor } = cqDetailInfo;
      const baseInfo: CqBaseInfoFormValue = {
        cqCode,
        cqName,
        systemCode,
        clstCode,
        appCode,
        auditor
      };
      setBaseInfo(baseInfo);
      setFormData(cqUndoTaskInfo);
    } else {
      Modal.warn({
        title: '警告',
        content: '非法访问，请检查数据',
        okText: '确定',
        onOk: () => goBack()
      });
    }
  }, []);

  const goLogin = () => {
    message.warning('不允许直接访问，请通过我的待办交易进入');
    history.replace('/user/login');
  }

  /**
   * 退出按钮
   */
  const goBack = () => {
    history.goBack();
  }

  const handleSubmit = (record: CqDetailInfoFormValue) => {
    console.log('Received values of form: ', record);
    // const queryParams = props.location.query;
    fillCqDetailInfo(record);
  }

  const fillCqDetailInfo = async (record: CqDetailInfoFormValue) => {
    // 与服务端通讯
    if (formData) {
      const { dispatch } = props;
      const { actTaskId, actInstId, cqId } = formData;
      const values: CqDetailInfoRecord = {
        actTaskId,
        actInstId,
        cqId,
        ...record
      };
      // 获取当前登录用户，作为任务处理人
      const res = await dispatch(FILL_CQ_DETAIL({
        ...values,
      }));
      if (res) {
        // 是否重置表单
        message.success('需求详细信息录入成功', 1)
        .then(() => onExit());
      }
    }
  }

  /**
   * 退出按钮
   */
  const onExit = () => {
    history.goBack();
  }

  const { auditorData, designerData, systemData, clusterData, appList, loading } = props;
  const { cqCode } = baseInfo;
  const detailInfo: CqDetailInfoFormValue = {
    ...EMPTY_CQ_DETAIL_INFO,
    cqCode
  };

  return(
    <PageContainer title='录入需求详细信息'>
      <Space direction='vertical' size='middle' style={{ display: 'flex' }}>
        <ProCard
          title='需求基本信息'
        >
          <CqBaseInfoForm
            colon={false}
            loading={false}
            auditorData={auditorData}
            systemData={systemData}
            clusterData={clusterData}
            appList={appList}
            formData={baseInfo}
          />
        </ProCard>
        <ProCard title='需求详细信息'>
          <CqDetailInfoForm
            colon={false}
            loading={loading}
            designerData={designerData}
            flag={'edit'}
            formData={detailInfo}
            onSubmit={handleSubmit}
            onCancel={onExit}
          />
        </ProCard>
      </Space>
    </PageContainer>
  );
}

export default connect(({ cqs, systems, users, loading }: ConnectState) => ({
  auditorData: users.auditorData,
  designerData: users.designerData,
  systemData: systems.systemData,
  clusterData: systems.clusterData,
  appList: cqs.appList,
  loading: loading.effects['workbenchs/fillCqDetailInfo'] || loading.effects['workbenchs/fetchCqDetailInitParams'],
}))(FillCqDetailInfo);